import 'package:flutter/material.dart';

class StarsWidget extends StatefulWidget {
  /**
   * currentSatars 当前平分数
   * maxStars 最大星数
   * unselectedStar 未选中星widget
   * selectedStar 选中星widget
   * count 星数量
   * unselectedStarColor 未选中星颜色
   * selectedStarColor 选中星的颜色
   * StarSize 星星size
   * */
  final double currentStars;
  final double maxStars;
  final Widget unselectedStar;
  final Widget selectedStar;
  final int count;
  final Color unselectedStarColor;
  final Color selectedStarColor;
  final double StarSize;

  StarsWidget({
    @required this.currentStars,
    this.maxStars = 10,
    unselectedStar,
    selectedStar,
    this.unselectedStarColor = const Color(0xffbbbbbb),
    this.selectedStarColor = const Color(0xffe0aa46),
    this.count = 5,
    this.StarSize = 30,
  })  : unselectedStar = unselectedStar ??
            Icon(
              Icons.star,
              size: StarSize,
              color: unselectedStarColor,
            ),
        selectedStar = selectedStar ??
            Icon(
              Icons.star,
              color: selectedStarColor,
              size: StarSize,
            );

  @override
  _StarsWidgetState createState() => _StarsWidgetState();
}

class _StarsWidgetState extends State<StarsWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
        child: Stack(
      children: <Widget>[
        Row(
            mainAxisSize: MainAxisSize.min,
            children:
                List.generate(widget.count, (index) => widget.unselectedStar)),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: getSelectedStars(),
        )
      ],
    ));
  }

  List<Widget> getSelectedStars() {
    //比例系数
    double proportion = widget.maxStars / widget.count;
    //算出整星
    int entireStars = (widget.currentStars / proportion).floor();
    //算出剩余的星
    double leftStar = widget.currentStars - entireStars * proportion;
    //算出剩余星占的比例
    double leftP = leftStar / proportion;

    //获得星星
    List<Widget> selectedStars = [];

    //整数
    for (int i = 0; i < entireStars; i++) {
      selectedStars.add(widget.selectedStar);
    }

    //小数
    Widget LeftStar = ClipRect(
      clipper: MyRectCliper(width: leftP* widget.StarSize),
      child: widget.selectedStar,
    );

    selectedStars.add(LeftStar);
//    print('${selectedStars.length}');
    return selectedStars;

  }
}

class MyRectCliper extends CustomClipper<Rect> {
  final double width;
  MyRectCliper({this.width});

  @override
  getClip(Size size) {
    // TODO: implement getClip
    return Rect.fromLTRB(0, 0, width, size.height);
  }

  @override
  bool shouldReclip(MyRectCliper oldClipper) {
    // TODO: implement shouldReclip
    return width != oldClipper.width;
  }
}
